<?php

class UsersController extends AppController {

    var $name = 'Users';
    var $belongsTo = array('Groups');
    var $user = array();
    var $helpers = array('Javascript', 'Session');
    var $components = array('Auth'); 
    //var $actsAs = array('Acl' => 'requester');
	
    function beforeFilter() {
        parent::beforeFilter(); 
        $this->Auth->mapActions(
            array(        
                'create' => array('register', 'admin_addUser'),        
                'read'   => array('show', 'admin_viewUsers'),        
                'update' => array('modify', 'admin_modifyUser'),        
                'delete' => array('delete', 'admin_deleteUser')    
            )
        );
        $this->Auth->allowedActions = array('*');
    }
    
    
    function login() {
		
    }

    function logout() {
		$this->Auth->logout();
        $this->redirect('/ftpfiles/index'); 
    }
	
	function show() {
		$userInfo = $this->User->find('first', 
            array(
                'conditions' => array(
				'User.id' => $this->Session->read('Auth.User.id')
                )
            )
		);
		$this->set('username', $userInfo['User']['username']);
		$this->set('nickname', $userInfo['User']['nickname']);
		$this->set('email', $userInfo['User']['email']);
		$this->set('theme', $userInfo['User']['theme']);

	}
	
    
	function modify() {
        
		$url = $this->referer();
		if (!empty($this->data)) {
			$hashPasswordForm = $this->Auth->hashPasswords($this->data['User']);
			$this->User->id = $this->Session->read('Auth.User.id');
      		if ($this->User->save($hashPasswordForm, false, array('username', 'password', 'nickname', 'email', 'theme'))) {
				$this->Session->write('Auth.User.nickname', $hashPasswordForm['nickname']);
				$this->Session->write('Auth.User.email', $hashPasswordForm['email']);
				$this->Session->write('Auth.User.theme', $hashPasswordForm['theme']);
				$this->redirect('/ftpfiles/index');
				return ;
      		} else {
        		$message = 'There was a problem with your information';
				$this->Session->setFlash($message, 'default', array('class' => 'flase')); 
				$this->redirect($url);
				return ;
      		}
   	 	}
	}
    
    function _build_aco() {
        $this->layout = 'ajax';
		if (!Configure::read('debug')) {
			return $this->_stop();
		}
		$log = array();

		$aco =& $this->Acl->Aco;
		$root = $aco->node('controllers');
		if (!$root) {
			$aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
			$root = $aco->save();
			$root['Aco']['id'] = $aco->id; 
			$log[] = 'Created Aco node for controllers';
		} else {
			$root = $root[0];
		}   

		App::import('Core', 'File');
		$Controllers = Configure::listObjects('controller');
		$appIndex = array_search('App', $Controllers);
		if ($appIndex !== false ) {
			unset($Controllers[$appIndex]);
		}
		$baseMethods = get_class_methods('Controller');
		$baseMethods[] = 'buildAcl';

		$Plugins = $this->_getPluginControllerNames();
		$Controllers = array_merge($Controllers, $Plugins);

		// look at each controller in app/controllers
		foreach ($Controllers as $ctrlName) {
			$methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));

			// Do all Plugins First
			if ($this->_isPlugin($ctrlName)){
				$pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
				if (!$pluginNode) {
					$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
					$pluginNode = $aco->save();
					$pluginNode['Aco']['id'] = $aco->id;
					$log[] = 'Created Aco node for ' . $this->_getPluginName($ctrlName) . ' Plugin';
				}
			}
			// find / make controller node
			$controllerNode = $aco->node('controllers/'.$ctrlName);
			if (!$controllerNode) {
				if ($this->_isPlugin($ctrlName)){
					$pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
					$aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
					$controllerNode = $aco->save();
					$controllerNode['Aco']['id'] = $aco->id;
					$log[] = 'Created Aco node for ' . $this->_getPluginControllerName($ctrlName) . ' ' . $this->_getPluginName($ctrlName) . ' Plugin Controller';
				} else {
					$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
					$controllerNode = $aco->save();
					$controllerNode['Aco']['id'] = $aco->id;
					$log[] = 'Created Aco node for ' . $ctrlName;
				}
			} else {
				$controllerNode = $controllerNode[0];
			}

			//clean the methods. to remove those in Controller and private actions.
			foreach ($methods as $k => $method) {
				if (strpos($method, '_', 0) === 0) {
					unset($methods[$k]);
					continue;
				}
				if (in_array($method, $baseMethods)) {
					unset($methods[$k]);
					continue;
				}
				$methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method);
				if (!$methodNode) {
					$aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
					$methodNode = $aco->save();
					$log[] = 'Created Aco node for '. $method;
				}
			}
		}
		if(count($log)>0) {
			debug($log);
		}
	}

	function _getClassMethods($ctrlName = null) {
		App::import('Controller', $ctrlName);
		if (strlen(strstr($ctrlName, '.')) > 0) {
			// plugin's controller
			$num = strpos($ctrlName, '.');
			$ctrlName = substr($ctrlName, $num+1);
		}
		$ctrlclass = $ctrlName . 'Controller';
		$methods = get_class_methods($ctrlclass);

		// Add scaffold defaults if scaffolds are being used
		$properties = get_class_vars($ctrlclass);
		if (array_key_exists('scaffold',$properties)) {
			if($properties['scaffold'] == 'admin') {
				$methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
			} else {
				$methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
			}
		}
		return $methods;
	}

	function _isPlugin($ctrlName = null) {
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) > 1) {
			return true;
		} else {
			return false;
		}
	}

	function _getPluginControllerPath($ctrlName = null) {
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) == 2) {
			return $arr[0].'.'.$arr[1];
		} else {
			return $arr[0];
		}
	}

	function _getPluginName($ctrlName = null) {
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) == 2) {
			return $arr[0];
		} else {
			return false;
		}
	}

	function _getPluginControllerName($ctrlName = null) {
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) == 2) {
			return $arr[1];
		} else {
			return false;
		}
	}

/**
 * Get the names of the plugin controllers ...
 * 
 * This function will get an array of the plugin controller names, and
 * also makes sure the controllers are available for us to get the 
 * method names by doing an App::import for each plugin controller.
 *
 * @return array of plugin names.
 *
 */
	function _getPluginControllerNames() {
		App::import('Core', 'File', 'Folder');
		$paths = Configure::getInstance();
		$folder =& new Folder();
		$folder->cd(APP.'plugins');

		// Get the list of plugins
		$Plugins = $folder->read();
		$Plugins = $Plugins[0];
		$arr = array();

		// Loop through the plugins
		foreach($Plugins as $pluginName) {
			// Change directory to the plugin
			$didCD = $folder->cd(APP . 'plugins'. DS . $pluginName . DS . 'controllers');
			// Get a list of the files that have a file name that ends
			// with controller.php
			$files = $folder->findRecursive('.*_controller\.php');

			// Loop through the controllers we found in the plugins directory
			foreach($files as $fileName) {
				// Get the base file name
				$file = basename($fileName);

				// Get the controller name
				$file = Inflector::camelize(substr($file, 0, strlen($file)-strlen('_controller.php')));
				if (!preg_match('/^'. Inflector::humanize($pluginName). 'App/', $file)) {
					if (!App::import('Controller', $pluginName.'.'.$file)) {
						debug('Error importing '.$file.' for plugin '.$pluginName);
					} else {
						/// Now prepend the Plugin name ...
						// This is required to allow us to fetch the method names.
						$arr[] = Inflector::humanize($pluginName) . "/" . $file;
					}
				}
			}
		}
		return $arr;
	}
    
    function _build_aro() {
        $aro = new Aro();
        
        $groups = array(
            0 => array(
                'model' => 'Group',
                'alias' => 'admin'
            ),
            1 => array(
                'model' => 'Group', 
                'alias' => 'radmin'
            ),
            2 => array(
                'model' => 'Group',
                'alias' => 'user'
            ),
        );
        
        foreach($groups as $data)
        {
            //Remember to call create() when saving in loops...
            $aro->create();
            
            //Save data
            $aro->save($data);
        }   
        
    }
    
    function admin_initDB() {
        // if(!$this->Acl->check(array('model' => 'Group', 'foreign_key' => $this->Session->read('Auth.User.group_id')), 'admin_initDB'))
            // return;
        $this->_build_aco();
        $this->_build_aro();
        $group =$this->User->Group;
        //Allow admins to everything
        $group->id = 1;     
        $this->Acl->allow($group, 'controllers');
 
        //allow managers to posts and widgets
        $group->id = 2;
        $this->Acl->deny($group, 'controllers');
        $this->Acl->allow($group, 'controllers/Users');
        $this->Acl->allow($group, 'controllers/Groups');
        $this->Acl->allow($group, 'controllers/Ftpfiles');
        $this->Acl->allow($group, 'controllers/Collections');
     
        //allow users to only add and edit on posts and widgets
        $group->id = 3;
        $this->Acl->deny($group, 'controllers');       
        $this->Acl->allow($group, 'controllers/Users/login');
        $this->Acl->allow($group, 'controllers/Users/logout');
        $this->Acl->allow($group, 'controllers/Users/modify');
        $this->Acl->allow($group, 'controllers/Collections');
        
        
        
        $message = '初始化成功';
        $this->Session->setFlash($message, 'default', array('class' => 'flase')); 
        $this->redirect('viewUsers');
    }
    
    function admin_viewUsers() {
        // if(!$this->Acl->check(array('model' => 'Group', 'foreign_key' => $this->Session->read('Auth.User.group_id')), 'admin_viewUsers'))
            // return;
        $usersInfo = $this->User->find('all');
        $this->set('userInfo', $usersInfo);
        
    }
    
    function admin_addUser() {
        // if(!$this->Acl->check(array('model' => 'Group', 'foreign_key' => $this->Session->read('Auth.User.group_id')), 'admin_addUser'))
            // return;
        $url = 'viewUsers';
        $Groups = $this->User->Group->find('all');
        $this->set('GroupsInfo', $Groups);
		if (!empty($this->data)) {
            $this->data['User']['createdate'] = date('Y-m-d H:i:s');
			$hashPasswordForm = $this->Auth->hashPasswords($this->data['User']);
      		if ($this->User->save($hashPasswordForm, false, array('username', 'password', 'nickname', 'email', 'theme','group_id', 'createdate'))) {
				$message = 'the user '.$this->User->id.' is saved';
				$this->Session->setFlash($message, 'default', array('class' => 'true')); 
      		} else {
        		$message = 'There was a problem';
				$this->Session->setFlash($message, 'default', array('class' => 'flase')); 
      		}
            $this->redirect($url);
   	 	}
    }
    
    function admin_deleteUser($id) {
        // if(!$this->Acl->check(array('model' => 'Group', 'foreign_key' => $this->Session->read('Auth.User.group_id')), 'admin_deleteUser'))
            // return;
        $url = 'viewUsers';
        if (!empty($id)) {
      		if ($this->User->del($id, false)) {
				$message = 'the user '.$id.' is deleted';
				$this->Session->setFlash($message, 'default', array('class' => 'true')); 
      		} else {
        		$message = 'There was a problem';
				$this->Session->setFlash($message, 'default', array('class' => 'flase')); 
      		}
            $this->redirect($url);
   	 	}
        return;
    }
    
    function admin_modifyUser($id) {
        // if(!$this->Acl->check(array('model' => 'Group', 'foreign_key' => $this->Session->read('Auth.User.group_id')), 'admin_modifyUser'))
            // return;
        $url = 'viewUsers';
        if($id == null){
            $this->redirect($url);
        }
        $Groups = $this->User->Group->find('all');
        $this->set('GroupsInfo', $Groups);
        $userInfo = $this->User->findById($id);
        $this->set('userInfo', $userInfo);
        if (!empty($this->data)) {
            if($this->data['User']['password']=='')
                unset($this->data['User']['password']);
            else
                $this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
            $this->User->id = $id;   
            if ($this->User->save($this->data, false)) {
                $message = 'the user '.$id.' is updated';
                $this->Session->setFlash($message, 'default', array('class' => 'true')); 
            } else {
                $message = 'There was a problem';
                $this->Session->setFlash($message, 'default', array('class' => 'flase')); 
            }
            $this->redirect($url);
        }
    }
    
    function checkP() {
        echo $this->Acl->check(array('model' => 'User', 'foreign_key' => 9), 'admin_viewUsers');
    }
	
}

?>
